package com.yznote.compileserver.terminal;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

import java.io.*;

public class TerminalSession {
    private static final Long timeout  = 500l;
    private TerminalSession(){

    }
    private Session session;
    public static TerminalSession getTerminalSession(Session session){
        TerminalSession terminalSession = new TerminalSession();
        terminalSession.session = session;
        return terminalSession;
    }
    public String sendCmd(String cmd) throws JSchException, IOException {
        ChannelExec channel = (ChannelExec) this.session.openChannel("exec");
        channel.setCommand(cmd);
        channel.setInputStream(null);
        channel.connect(timeout.intValue());
        BufferedReader reader = new BufferedReader(new InputStreamReader(channel.getInputStream()));
        String line = null;
        String resp = "";
        while ((line = reader.readLine()) != null) {
            resp += line + "\n";
        }
        if (resp != null && !resp.equals("")) {
            resp = resp.substring(0, resp.length() - 1);
        }
        channel.disconnect();
        reader.close();
        return resp;
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        this.session.disconnect();
    }
}
